import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';

import {API_PREFIX, RESPONSE_TYPE} from "../../config/constant";
import {getToken} from "./auth";
import {useUserStore} from "../store/modules/user";
import {responseData} from "../api/global";
import {Toast} from "vant";



const BASE_URL = import.meta.env.MODE === 'development' ? API_PREFIX :''

const instance = axios.create({
    baseURL:BASE_URL,
    withCredentials:true,
    timeout:1000
})

// 请求拦截器
instance.interceptors.request.use(
    (config)=>{
        const token = getToken();
        if(token){
            config.headers = {
                ...config.headers,
                Authorization: token,
            }
        }
        // debugger
        return config
    },
    error => {
        console.log('请求拦截器报错',error)
        return Promise.resolve(error);
    }
)

// 响应拦截器
instance.interceptors.response.use(
    (response)=>{
        const res = response.data as responseData<any>

        // 返回200正常返回
        if(res.code === RESPONSE_TYPE.success){
            return res.data || true
        }
        // 登录失效
        if(res.code === RESPONSE_TYPE.fail){
            useUserStore().loginOut().catch(err=>console.log(err));
            return
        }
        if(res.code === RESPONSE_TYPE.error){
            // 弹出错误信息
            // useToast({message:'出现错误'})
            Toast.fail('出现错误')
        }
    },
    error => {
        console.log('响应拦截器'+error)
    }
)

// 设置请求方法
// 有待考虑的错版方法
const requset = <T = any>(config:AxiosRequestConfig,options?:AxiosRequestConfig):Promise<T>=>{
    if(typeof config === 'string'){
        if(!options){
            return instance.request<T,T>({
                url:config,
            })
        }else {
            return instance.request<T,T>({
                url:config,
                ...options
            })
        }
    }else {
        return instance.request<T,T>(config)
    }
}

export function get<T = any>(config: AxiosRequestConfig, options?: AxiosRequestConfig):Promise<T>{
    return requset({...config,method:'GET'},options);
}

export function post<T = any>(config: AxiosRequestConfig, options?: AxiosRequestConfig):Promise<T>{

    return requset({...config,method:'POST'},options)
}

export default requset;
export type {AxiosInstance,AxiosResponse}




